package com.xxxx.server.controller;

import com.xxxx.server.pojo.Admin;
import com.xxxx.server.pojo.AdminLoginParams;
import com.xxxx.server.pojo.RespBean;
import com.xxxx.server.service.IAdminService;
import com.xxxx.server.service.impl.UploadUserFaceService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.LinkedHashMap;

/**
 * 登录
 *
 * @author zhoubin
 * @since 1.0.0
 */
@RestController
public class LoginController {

	@Autowired
	private IAdminService adminService;
	@Autowired
	private UploadUserFaceService faceService;

	@ApiOperation(value = "登录")
	@PostMapping("/login")
	public RespBean login(@RequestBody AdminLoginParams adminLoginParams, HttpServletRequest request) {
		return adminService.login(adminLoginParams.getUsername(), adminLoginParams.getPassword()
			,adminLoginParams.getCode(),request);
	}

	@ApiOperation(value = "获取用户对象")
	@GetMapping("/admin/info")
	public Admin adminInfo(Principal principal) {
		if (null == principal) {
			return null;
		}
		String username = principal.getName();
		Admin admin = adminService.getAdminByUserName(username);
		if (null == admin) {
			return null;
		}
		admin.setRoles(adminService.getRoles(admin.getId()));
		admin.setPassword(null);
		return admin;
	}


	@ApiOperation(value = "退出登录")
	@PostMapping("/logout")
	public RespBean logout() {
		return RespBean.success("注销成功！");
	}


	@PutMapping("/admin/info")
	@ApiOperation("修改用户信息")
	public RespBean editAdminInfo(@RequestBody LinkedHashMap<String,Object>  map) {
		final boolean b = adminService.updateAdminInfo(map);
		if(b){
			return RespBean.success("用户信息修改成功！");
		}else{
			return RespBean.success("用户信息修改失败！");
		}
	}

	@PutMapping("/admin/pass")
	@ApiOperation("修改用户密码信息")
	public RespBean editAdminPasswordInfo(@RequestBody LinkedHashMap<String,Object>  map) {
		final boolean b = adminService.updateAdminPasswordInfo(map);
		if(b){
			return RespBean.success("用户信息修改成功！");
		}else{
			return RespBean.success("用户信息修改失败！");
		}
	}

	@ApiOperation("修改用户头像")
	@PostMapping("/admin/userface")
	public void editUserFace(@RequestBody MultipartFile file){
		//头像修改后访问的路径
		final String path = faceService.saveUploadImage(file);
		//需要将当前用户的头像地址修改为新的
		final Integer id = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
		adminService.updateAdminUserFaceById(id, path);
	}
}